import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter_douban/main_page/class/model/class_item_model.dart';
import 'package:fluttertoast/fluttertoast.dart';

class ClassProviderModel extends ChangeNotifier {
  final List<ClassItemModel> _items = [];
  bool _itemStates = false;

  /// 禁止改变已购买课程的商品信息
  UnmodifiableListView<ClassItemModel> get items =>
      UnmodifiableListView(_items);

  /// 已购买课程数量
  int get count => _items.length;
  /// 获取购买状态
  bool get states => _itemStates;

  /// 判断课程是否添加到已购买中。
  void changeStates(ClassItemModel item) {
    int count = 0;
    for (int i = 0; i < _items.length; i++) {
      ClassItemModel model = _items[i];
      if (model.id == item.id) {
        count++;
      }
    }
    if(count == 0){
      _itemStates = false;
    }else{
      _itemStates = true;
    }
    /// 通知监听器（订阅者），重新构建InheritedProvider， 更新状态。
    notifyListeners();
  }

  /// 将课程添加到已购买中。
  void add(ClassItemModel item) {
    _itemStates = true;
    for (int i = 0; i < _items.length; i++) {
      ClassItemModel model = _items[i];
      if (model.id == item.id) {
        Fluttertoast.showToast(
            msg: "您已经购买了~",
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.black87,
            textColor: Colors.white,
            fontSize: 14.0);
        return;
      }
    }
    _items.add(item);

    /// 通知监听器（订阅者），重新构建InheritedProvider， 更新状态。
    notifyListeners();
  }
}
